package com.zerui.manager.app.device.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.zerui.cola.dto.SingleResponse;
import com.zerui.devicemanager.provider.DeviceDubboService;
import com.zerui.devicemanager.provider.cmd.DeviceSummaryCmd;
import com.zerui.devicemanager.provider.dto.SummaryDTO;
import com.zerui.manager.devicegroup.DeviceGroup;
import com.zerui.manager.devicegroup.domainservice.DeviceGroupRepository;
import com.zerui.manager.web.cmd.DeviceInfoCmd;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author wh
 * @create_time 2023-08-25 10:46
 */
@Component
@CatchAndLog
public class DeviceSummaryCmdExe {

    @DubboReference
    private DeviceDubboService deviceDubboService;
    @Value("${spring.application.name}")
    private String applicationName;
    @Resource
    private DeviceGroupRepository deviceGroupRepository;

    public SingleResponse<SummaryDTO> execute(DeviceInfoCmd deviceInfoCmd) {
        Set<String> deviceIds = null;
        if(ObjectUtils.isNotEmpty(deviceInfoCmd.getOrgId())){
            DeviceGroup deviceGroup = deviceGroupRepository.selectById(deviceInfoCmd.getOrgId());
            if(ObjectUtils.isNotEmpty(deviceGroup)){
                deviceIds = deviceGroup.getDeviceIds();
            }
        }
        SingleResponse<SummaryDTO> response = deviceDubboService.summary(createDeviceCmd(deviceInfoCmd,deviceIds));
        response.getData().setDeviceIds(null);
        return response;
    }

    private DeviceSummaryCmd createDeviceCmd(DeviceInfoCmd deviceInfoCmd, Set<String> deviceIds) {
        DeviceSummaryCmd cmd = new DeviceSummaryCmd();
        cmd.setBizUnit(applicationName);
        cmd.setDeviceIds(CollectionUtils.isEmpty(deviceIds) ? null : deviceIds.stream().map(Long::parseLong).collect(Collectors.toList()));
        cmd.setName(deviceInfoCmd.getName());
        cmd.setPositionCmd(deviceInfoCmd.getPositionCmd());
        cmd.setCode(deviceInfoCmd.getCode());
        cmd.setStatus(deviceInfoCmd.getStatus());
        cmd.setType(deviceInfoCmd.getType());
        return cmd;
    }
}
